﻿using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace DimensionsHelper.Common.Utils.Converters;

public class ColorJsonConverter : JsonConverter<Color>
{
    private static bool IsKnownColorName(string colorName)
    {
        return !GetHexNumberFormatColorRegex().IsMatch(colorName);
    }

    public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        string? text = reader.GetString();

        if (string.IsNullOrWhiteSpace(text) || text!.Trim() == "0")
        {
            return Color.Empty;
        }

        if (IsKnownColorName(text))
        {
            return Color.FromName(text);
        }

        try
        {
            int a = int.Parse(text.Substring(0, 2), NumberStyles.HexNumber);
            int r = int.Parse(text.Substring(2, 2), NumberStyles.HexNumber);
            int g = int.Parse(text.Substring(4, 2), NumberStyles.HexNumber);
            int b = int.Parse(text.Substring(6, 2), NumberStyles.HexNumber);
            return Color.FromArgb(a, r, g, b);
        }
        catch
        {
            throw new Exception($"颜色'{text}'转换失败，需要是颜色名称或ARGB值。");
        }
    }

    public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.IsNamedColor ? value.Name : $"{value.A:X}{value.R:X}{value.G:X}{value.B:X}");
    }
    
    
    private static Regex? _hexNumberFormatColorRegex;

    private static Regex GetHexNumberFormatColorRegex() =>
        _hexNumberFormatColorRegex ??= new Regex(@"([0-9a-fA-F]{2}){4}");
}